package jfood.restaurant;

import jade.content.lang.Codec;
import jade.content.lang.Codec.CodecException;
import jade.content.lang.sl.SLCodec;
import jade.content.onto.Ontology;
import jade.content.onto.OntologyException;
import jade.content.onto.basic.Action;
import jade.core.AID;
import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.Property;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jfood.gui.MainHole;
import jfood.ontology.query.QueryOntology;
import jfood.ontology.query.StartWaiterAction;

public class RestaurantAgent extends Agent {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2235830525466070096L;
	
	protected Codec codec = new SLCodec();
	protected Ontology queryOntology = QueryOntology.getInstance();
	
	protected void setup() {
		getContentManager().registerLanguage(codec);
		getContentManager().registerOntology(queryOntology, QueryOntology.NAME);
		MainHole window = new MainHole(this);
		window.setVisible(true);
	}
	
	public boolean spawnWaiter() {
		StartWaiterAction action = new StartWaiterAction();
		
		ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
		msg.setLanguage(this.codec.getName());
		msg.setOntology(this.queryOntology.getName());
		AID chef = getWaiter();
		if (chef == null)
		{
			return false;
		}
		try {
			this.getContentManager().fillContent(msg, new Action(chef, action));
		} catch (CodecException e) {
			e.printStackTrace();
		} catch (OntologyException e) {
			e.printStackTrace();
		}
		msg.addReceiver(chef);
		this.send(msg);
		return true;
	}
	
    private AID getWaiter()
    {
    	DFAgentDescription template = new DFAgentDescription();
		ServiceDescription templateSd = new ServiceDescription();
		templateSd.setType("meal-serving");
		templateSd.addProperties(new Property("country", "Poland"));
		template.addServices(templateSd);
     	try {
     		DFAgentDescription[] result = DFService.search(this, template);
     		if (result.length > 0)
     		{
     			return result[0].getName();
     		}
    	}
    	catch (FIPAException ex) {
    		ex.printStackTrace();
    	}
		return null;
    }
}
